<?php
namespace Admin\Controller;
use Think\Controller;
class GoodsController extends CommonController {

	public function _initialize(){
		parent::_initialize();
	}
	//显示添加商品信息界面
	public function newGoods(){
		$Sort = M("Sort");
		$sortdata = $Sort->order("id ASC")->select();
		$this->assign("sortlist",$sortdata);
	       	$this->display("addgoods");
	}
	//显示编辑商品信息界面
	public function editGoods(){
		$goods_id = I("get.goods_id");
		$Goods = M("Goods");
		$Goodsdata = $Goods->where("id ={$goods_id} ")->find();
		$Sort = M("Sort");
		$TwoSort = M("Twosort");
		//找出一级分类
		$Goodsdata['sortname'] = $Sort->where("id = {$Goodsdata['sortid']}")->getField("sortname");
		//找出二级分类
		$Goodsdata['twosortname'] = $TwoSort->where("id = {$Goodsdata['twosortid']}")->getField("twosortname");
		//找出所有二级分类
		$Goodsdata['twosortlist'] = $TwoSort->where("sortid ={$Goodsdata['sortid']} ")->select();
		//商品图片转码
		$Goodsdata['goodsimg'] = json_decode($Goodsdata['goodsimg'],true);
		$sortdata = $Sort->order("id ASC")->select();
		$this->assign("sortlist",$sortdata);
		//用于判断是否是编辑商品信息
		$this->assign("goodstag",$goods_id);
		$this->assign("Goodsdata",$Goodsdata);
		$this->display("addgoods");
	}

	//保存编辑后的商品信息
	public function savegoods(){
		$Goods = M('Goods');

		$checkrules = array(
 			array('goodsname','require','商品名称必须填写！'), // 商品名称必须
 			array('goodsorig','require','商品原价必须填写！'), // 商品原价必须
 			array('goodsnow','require','商品现价必须填写！'), // 商品现价必须
 			array('goodsdetail','require','商品现价必须填写！'), // 商品详情必须
 			//array('sortname','','商品分类已经存在！',1,'unique',1), // 验证商品分类是否已经存在
 			array('sortid', '/^[1-9]\d*$/', '请选择一级分类！', 1, 'regex', 3), //验证是否选择一级分类
 			array('twosortid', '/^[1-9]\d*$/', '请选择二级分类！', 1, 'regex', 3), //验证是否选择一级分类
			array('createdate','require','发布时间必须填写！'), // 修改时间必须
		);
		$data=$Goods ->validate($checkrules)->create();
		if (!$data) {
			$this->error($Goods->getError());
		}else{
			$goodsimg=I('post.imgs','','');
			if (empty($goodsimg)) {
				$this->error("请上传商品图片！");
			}else{
				$data['goodsimg']  =  json_encode($goodsimg);
				$data['goodsdetail'] = I("post.goodsdetail",'','');
				//判断是否是添加新分类或者编辑分类
				$goods_id = I("get.goods_id");

				if (empty($goods_id)) {
					$ret=$Goods->where("goodsname ='{$data['goodsname']}' ")->find();
					if ($ret) {
						$this->error("商品已经存在！");
					}else{
						$res=$Goods->add($data);
					}
				}else{
					$res = $Goods->where("id ={$goods_id}")->save($data);
				}
				if (!$res) {
					$this->error("请确认商品信息是否填写正确！");
				}else{
					$this->success("保存商品信息成功！");
				}
				
			}
			
		}
	}
	
	//删除商品
	public function delGoods(){
		$goods_id = I("get.goods_id");
		$Goods = M('Goods');
		$res=$Goods->where("id ={$goods_id}")->delete();
		if ($res) {
			$this->success("删除商品成功");
		}else{
			$this->error("删除商品失败");
		}
	}
}